package com.allwees.bs.c.module.order.entity;

import com.baomidou.mybatisplus.annotation.FieldStrategy;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.allwees.bs.c.module.base.entity.JpaBaseEntity;
import com.allwees.bs.c.module.order.req.CartItemReq;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * 购物车
 *
 * @author yangylsky
 *
 */
@Data
@EqualsAndHashCode(callSuper = true)
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "o_cart")
@TableName("o_cart")
public class CartEntity extends JpaBaseEntity {

	private static final long serialVersionUID = -2039307259245396150L;

	@Column(length = 64)
    private String userUuid;

    //币种
    private String currency;

    private Integer locked = 0;

	@Column(length = 64)
	@TableField(updateStrategy = FieldStrategy.IGNORED)
	private String userCouponUuid;

	@Column(length = 64)
	@TableField(updateStrategy = FieldStrategy.IGNORED)
	private String userCouponNo;

	@Column(length = 64)
	@TableField(updateStrategy = FieldStrategy.IGNORED)
	private String promoCode;

	@Column(length = 64)
	@TableField(updateStrategy = FieldStrategy.IGNORED)
	private String userPromoLogUuid;

	private BigDecimal amtCash;

    @Transient
	@TableField(exist=false)
	private List<CartItemEntity> items = new ArrayList<>();

    public Integer sum() {
    	return items.stream().mapToInt(CartItemEntity::getQuantity).sum();
    }

    public BigDecimal amount() {
    	return new BigDecimal(items.stream().mapToDouble(item -> item.amount().doubleValue()).sum());
    }

	public CartItemEntity addItem(CartItemReq itemReq) {
		CartItemEntity item = findItemBySkuUuid(itemReq.getSkuUuid());
		if(item == null) {
			item = new CartItemEntity(itemReq);
			item.setCartUuid(getUuid());
			items.add(item);
		} else {
			item.setQuantity(item.getQuantity() + itemReq.getQuantity());
		}
		return item;
	}

	private CartItemEntity findItemBySkuUuid(String skuUuid) {
		for(CartItemEntity item : items) {
			if(item.getSkuUuid().equals(skuUuid)) {
				return item;
			}
		}
		return null;
	}
}
